import * as api from '../../api/common';

Page({
  data: {
    phoneNumber: '',
    verificationCode: '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    countdown: 0,
    timer: null,
    showVerification: false,
  },

  onLoad(options) {
    // 获取缓存中的用户信息
    const userInfo = tt.getStorageSync('info');
    if (userInfo) {
      this.setData({
        phoneNumber: userInfo.phone
      });
    }
  },

  onUnload() {
    // 页面卸载时清除定时器，避免内存泄漏
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 输入验证码
  inputVerificationCode(e) {
    this.setData({
      verificationCode: e.detail.value
    });
  },

  // 输入原密码
  inputOldPassword(e) {
    this.setData({
      oldPassword: e.detail.value
    });
  },

  // 输入新密码
  inputNewPassword(e) {
    this.setData({
      newPassword: e.detail.value
    });
  },

  // 输入确认密码
  inputConfirmPassword(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  // 校验手机号格式
  checkPhoneNumber(phoneNumber) {
    const reg = /^1\d{10}$/;
    return reg.test(phoneNumber);
  },

  // 发送验证码
  async sendVerificationCode() {
    const phoneNumber = this.data.phoneNumber.trim();

    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return;
    }

    try {
      const response = await api.sendVerificationCode({
        phone: phoneNumber
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });
      } else {
        tt.showToast({
          title: '验证码发送成功',
          icon: 'success'
        });

        this.setData({
          showVerification: true
        });

        this.startCountdown();
      }
    } catch (error) {
      tt.showToast({
        title: '验证码发送失败，请重试',
        icon: 'none'
      });
      console.error('Failed to send verification code:', error);
    }
  },

  // 开始倒计时
  startCountdown() {
    let count = 60;
    this.setData({
      countdown: count
    });

    this.data.timer = setInterval(() => {
      count--;
      if (count >= 0) {
        this.setData({
          countdown: count
        });
      } else {
        clearInterval(this.data.timer);
        this.setData({
          countdown: 0
        });
      }
    }, 1000);
  },

  // 提交表单
  async formSubmit() {
    const { phoneNumber, verificationCode, oldPassword, newPassword, confirmPassword } = this.data;

    if (!this.checkPhoneNumber(phoneNumber)) {
      tt.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      });
      return;
    }

    if (!verificationCode) {
      tt.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }

    if (!oldPassword) {
      tt.showToast({
        title: '请输入原密码',
        icon: 'none'
      });
      return;
    }

    if (newPassword.length < 6) {
      tt.showToast({
        title: '新密码长度至少为6位',
        icon: 'none'
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      tt.showToast({
        title: '两次输入的新密码不一致',
        icon: 'none'
      });
      return;
    }

    try {
      const response = await api.updatePassword({
        phone: phoneNumber,
        code: verificationCode,
        oldPassword: oldPassword,
        newPassword: newPassword
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg,
          icon: 'none'
        });
      } else {
        tt.showToast({
          title: '密码修改成功',
          icon: 'success'
        });

        // 密码修改成功后的操作，例如跳转到登录页面
        tt.navigateTo({
          url: '../loginByAccount/index'
        });
      }
    } catch (error) {
      tt.showToast({
        title: error,
        icon: 'none'
      });
    }
  }
});
